package com.lyj.sc.aliyuntianchi.test20220714;

import java.util.Stack;

/**
 * @Author: liyangjing
 * @Date: 2022/07/14/22:18
 * @Description:
 */
public class test4 {
    //输 入： s = "3+2*2"
    //输出：7
    public static int calculate(String s) {
        //使用栈来计算
        Stack<Integer> stack = new Stack<>();
        char preSing = '+';
        int num = 0;
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if(Character.isDigit(chars[i])) {
                num = num * 10 + chars[i] - '0';
            }
            System.out.println(chars[i]);
            if(!Character.isDigit(chars[i]) && chars[i]!=' ' || i==chars.length-1){
                switch (preSing){
                    case '+':
                        stack.push(num);
                        break;
                    case '-':
                        stack.push(-num);
                        break;
                    case '*':
                        stack.push(stack.pop()*num);
                        break;
                    default:
                        stack.push(stack.pop()/num);
                        break;
                }
                preSing=chars[i];
                num=0;
            }
        }
        int sum=0;
        while (!stack.isEmpty()){
            sum+=stack.pop();
        }
        return sum;
    }

    public static void main(String[] args) {
        calculate("3+2*2");
    }
}
